package com.zyit.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.zyit.dto.AliPay;
import com.zyit.pojo.PaymentInfo;
import com.zyit.service.OrderInfoService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class OrderPayController {

    @Autowired
    private OrderInfoService orderInfoService;

    //请求支付页面
    @GetMapping("/pay")
    public String pay(AliPay aliPay){
        AlipayTradePagePayResponse response;
        try {
            response = Factory.Payment.Page()
                    .pay(aliPay.getSubject(),aliPay.getTraceNo(),aliPay.getTotalAmount(),"");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response.getBody();
    }


    //支付成功回调
    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            //使用map存储请求参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                 System.out.println(name + " = " + request.getParameter(name));
            }

            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                PaymentInfo info = new PaymentInfo();
                info.setOutTradeNo(params.get("out_trade_no"));//商户订单号
                info.setOrderId(Long.valueOf(params.get("out_trade_no")));//订单号
                info.setPaymentType(2L);//支付宝支付
                info.setTradeNo(params.get("trade_no"));//交易凭证
                info.setTotalAmount(Double.valueOf(params.get("total_amount")));//支付金额
                info.setSubject(params.get("subject"));//交易内容
                info.setPaymentStatus(params.get("trade_status")=="TRADE_SUCCESS"?1L:2L);//支付状态
                info.setCallbackTime(LocalDateTime.parse(params.get("gmt_payment"),DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));//付款时间

                // 更新订单状态
                orderInfoService.changeOrderStatus(info);
            }
        }
        return "success";
    }

}
